package com.ymm.lulutong.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.ymm.lulutong.constants.*;
import com.ymm.lulutong.domain.ShipperNoticeDomainService;
import com.ymm.lulutong.entity.CargoOpsLog;
import com.ymm.lulutong.entity.ComplaintOpsLog;
import com.ymm.lulutong.entity.Notice;
import com.ymm.lulutong.mapper.ShipperCargoOpsLogMapper;
import com.ymm.lulutong.mapper.ShipperComplaintOpsLogMapper;
import com.ymm.lulutong.mq.consumer.msg.CargoPutOnMsg;
import com.ymm.lulutong.mq.consumer.msg.ComplaintCompleteMsg;
import com.ymm.lulutong.websocket.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.topic.complaint}", consumerGroup = "${mq.consumer.groupname.complaint.complete}", selectorExpression = "complete", maxReconsumeTimes = 3)
public class ComplaintCompleteMsgConsumer implements RocketMQListener<MessageExt> {
    @Resource
    private ShipperComplaintOpsLogMapper shipperComplaintOpsLogMapper;

    @Resource
    private WebSocket webSocket;

    @Resource
    private ShipperNoticeDomainService shipperNoticeDomainService;


    @Override
    public void onMessage(MessageExt messageExt) {
        //解析消息内容
        String body = new String(messageExt.getBody(), StandardCharsets.UTF_8);
        ComplaintCompleteMsg complaintCompleteMsg = JSON.parseObject(body, ComplaintCompleteMsg.class);
        System.out.println("监听到消息" + complaintCompleteMsg);
        if (Objects.isNull(complaintCompleteMsg)) {
            log.info("ComplaintCompleteMsg为空！");
            return;
        }
        Long complaintsId = complaintCompleteMsg.getComplaintsId();
        Long shipperId = complaintCompleteMsg.getComplaintId();
        Integer opsType = ComplaintOpsEnum.COMPLETE.getCode();
        if (Objects.isNull(complaintsId) || Objects.isNull(shipperId)) {
            log.info("参数为空！");
            return;
        }

        ComplaintOpsLog complaintOpsLog = new ComplaintOpsLog();
        complaintOpsLog.setComplaintsId(complaintsId);
        complaintOpsLog.setShipperId(shipperId);
        complaintOpsLog.setOrderId(complaintCompleteMsg.getOrderId());
        complaintOpsLog.setOpsType(opsType);
        complaintOpsLog.setOpsPersonType(complaintCompleteMsg.getOpsPersonType());
        complaintOpsLog.setOpsPersonId(complaintCompleteMsg.getOpsPersonId());
        complaintOpsLog.setCreateTime(new Date());
        complaintOpsLog.setUpdateTime(new Date());
        complaintOpsLog.setExecutionStatus(MessgeStatusEnum.IN_EXECUTION.getCode());

        //保存到数据库
        try {
            shipperComplaintOpsLogMapper.add(complaintOpsLog);
        } catch (Exception e) {
            if (!Objects.isNull(shipperComplaintOpsLogMapper.getLogIdByShipperIdAndComplaintsIdAndOpsType(shipperId, complaintsId, opsType))) {
                log.info(complaintOpsLog.getLogId() + "消息已经被消费过");
                return;
            } else {
                log.info("数据库错误");
                //重试
                throw e;
            }
        }

        //投递通知
        try {
            Notice notice = new Notice();
            notice.setShipperId(shipperId);
            notice.setContent("您的申诉已完成处理。");
            notice.setFromPersonType(complaintCompleteMsg.getOpsPersonType());
            notice.setFromPersonId(complaintCompleteMsg.getOpsPersonId());
            notice.setNoticeType(NoticeTypeEnum.AGENT_NOTICE.getCode());
            notice.setAdditionalInformation("{\"orderId\":" + complaintCompleteMsg.getOrderId() + ", \"compaintsId\":" + complaintsId + "}");
            shipperNoticeDomainService.saveNotice(notice);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //WebSocket通知
        try {
            webSocket.sendOnMessage(shipperId, "您的申诉已完成处理");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //设置业务执行状态为完成
        shipperComplaintOpsLogMapper.updateExecutionStatusByLogId(complaintOpsLog.getLogId(), MessgeStatusEnum.COMPLETED.getCode());

    }
}
